package logic

import (
	"fmt"
	"time"

	"gitee.com/firewing_group/configenv"

	"gitee.com/firewing_group/model/ctxdata"
	"gitee.com/firewing_group/model/model/stadvertisement"
	"gitee.com/firewing_group/model/model/stuser"
)

func GetAide(cc *ctxdata.Cusctx, user *stuser.KuaiMaoUser, _adNumberLimt, _adNumber, _rewarduplimit, _rewarddownlimit, _timeboom, _whatboom int) (*stadvertisement.Advertisement, error) {
	lastAd := stadvertisement.GetLastAds(cc, 2, user.UserName)
	//今天凌晨的时间都大于创建时间，说明要创建新的
	clickfactor := configenv.GetEnvAsIntWithDefault("clickfactor", 200)
	if lastAd == nil || TodayTime(cc) > lastAd.CreateTime {
		lastAd = stadvertisement.NewAd(cc, 2, user.UserName, 1, _timeboom, _whatboom, clickfactor)
	} else {
		//判断是不是最大组数，判断是否都看过
		if lastAd.Number != _adNumberLimt/_adNumber {
			if lastAd.Inform["1"].IsRewarded && lastAd.Inform["2"].IsRewarded {
				lastAd = stadvertisement.NewAd(cc, 2, user.UserName, lastAd.Number+1, _timeboom, _whatboom, clickfactor)
			}
		} else {
			if lastAd.Inform["1"].IsRewarded && lastAd.Inform["2"].IsRewarded {
				err := fmt.Errorf("%s", "ALL_AD_OVER")
				cc.Errf("err:%v", err)
				return nil, err
			}
		}
	}
	cc.Logf("第轮_%v", lastAd.Number)
	lastAd.UpReward = _rewarduplimit * configenv.GetEnvAsIntWithDefault("clickfactor", 240) / 100
	lastAd.DownReward = _rewarddownlimit
	lastAd.Inform["1"].Base = 100
	lastAd.Inform["2"].Base = 100
	return lastAd, nil
}

func TodayTime(cc *ctxdata.Cusctx) int64 {
	timenow := time.Now()
	loc, _ := time.LoadLocation("Local")
	time_day_data := time.Date(timenow.Year(), timenow.Month(), timenow.Day(), 0, 0, 0, 0, loc)
	time_day := time_day_data.Unix()
	return time_day //每天00:00:00的时间戳
}
